import _ from 'lodash';
import axios from 'axios';
import channels from './Channels';
import assert from 'assert';

class RequestService {
    constructor(env) {
        this.channel = env;
        this.axios = axios.create({
            baseURL: channels.find(c => c.value === env).endpoint,
        });

        this.axios.interceptors.request.use(options => {
            const authToken = localStorage.getItem('auth-token');
            if (authToken !== undefined && authToken !== null) {
                options.headers = { 'Authorization': `Bearer ${authToken}` };
            }
            return options;
        });
    }

    async login(username, password) {
        const res = await this.axios.post('/auth/signin', {
            "username": username, "credential": password, "useVerificationCode": false
        });

        const token = res.data.token;
        return { channel: this.channel, token };
    }

    async getTenants() {
        const res = await this.axios.get('/api/v1/tenants');
        return res.data;
    }

    async enableTenant(id, enabled) {
        const res = await this.axios.patch(`/api/v1/tenants/${id}`, { enabled });
        return res.data;
    }

    async createNewTenant(tenant) {
        const res = await this.axios.post(`/api/v1/tenants`, tenant);
        return res.data;
    }
}

const envCaches = {};
const Requests = {
    env(name) {
        assert(channels.map(c => c.value).includes(name), `env ${name} not support`);

        if (envCaches[name] === undefined) {
            envCaches[name] = new RequestService(name);
        }

        return envCaches[name];
    },
    current() {
        if (_.isNil(this._current)) {
            assert(!_.isNil(localStorage.getItem('auth-token')) && !_.isNil(localStorage.getItem('channel')), 'no auth token or channel');
            this._current = this.env(localStorage.getItem('channel'));
        }

        return this._current;
    }
};

export default Requests;